package com.jcl.cloud.services.unicrawler.service;


import com.google.common.base.Strings;
import com.jcl.cloud.common.service.exception.JclCrawlException;
import com.jcl.cloud.services.gateway.common.task.BuyResumeReq;
import com.jcl.cloud.services.gateway.common.task.BuyResumeRsp;
import com.jcl.cloud.services.unicrawler.common.dto.CrawlTask;
import com.jcl.cloud.services.unicrawler.common.dto.CrawlTaskMgrReq;
import com.jcl.cloud.services.unicrawler.task.CrawlerTaskHandler;
import com.netflix.astyanax.util.TimeUUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class CrawlerManageService {
    private static final Logger logger = LoggerFactory.getLogger(CrawlerManageService.class);


    @Autowired
    private CrawlerTaskHandler crawlerTaskHandler;


    public CrawlTask createCrawlTask(CrawlTaskMgrReq taskMgrReq) throws JclCrawlException {
        //验证cron表达式以及账号是否登录成功
        this.validateReq(taskMgrReq);



        //生成唯一的crawlerId
        String crawlerId = TimeUUIDUtils.getUniqueTimeUUIDinMicros().toString();



        CrawlTask crawlTask = new CrawlTask();
        crawlTask.setCrawlerId(crawlerId);
        crawlTask.setTenantId(taskMgrReq.getTenantId());
        crawlTask.setAccountKey(taskMgrReq.getAccountKey());


        crawlTask.setSiteCode(taskMgrReq.getSiteCode());
        crawlTask.setTaskType(taskMgrReq.getTaskType());
        crawlTask.setLevel(taskMgrReq.getLevel());
        crawlTask.setCron(taskMgrReq.getCron());

        crawlTask.setAccount(taskMgrReq.getAccount());

        crawlTask.setUserName(taskMgrReq.getUserName());

        crawlTask.setPassWord(taskMgrReq.getPassWord());




        //保存任务
        this.crawlerTaskHandler.addTask(crawlTask);





        return crawlTask;
    }



    public BuyResumeRsp buyResume(BuyResumeReq buyResumeReq) throws JclCrawlException{


        BuyResumeRsp buyResumeRsp =  this.crawlerTaskHandler.buyResume(buyResumeReq);

        return  buyResumeRsp;
    }



    protected void validateReq(CrawlTaskMgrReq taskMgrReq) throws JclCrawlException {

        String taskId = taskMgrReq.getTaskId();
        if(Strings.isNullOrEmpty(taskId)){
            taskId = TimeUUIDUtils.getUniqueTimeUUIDinMicros().toString();
            taskMgrReq.setTaskId(taskId);
            logger.info("Request Without TaskId, Generated TaskId:{}", taskMgrReq.getTaskId());
            MDC.put("taskId", taskId);
        }else {
            try {
                TimeUUIDUtils.getTimeFromUUID(UUID.fromString(taskId));
            } catch (UnsupportedOperationException var11) {
                throw new JclCrawlException();
            }
        }



    }




}
